import { mapMutations } from 'vuex'
import { SocketUrl } from '@/common/chat_config.js'
import Dayjs from '@/common/dayjs.min.js'

const CallBack=[
	'userLogin',
	'updateInfo',
	'recordConversation',
	'recordUserList',
	'recordList',
	'recordLastReading',
	'addRequest',
	'agreeBuddy',
	'userRequestList'
];
const mapArray = CallBack.map(item=>{
	return 'chat/'+item
})

export default {
	computed:{
		isSocketOpen:{
			get(){
				return this.$store.state.chat.isSocketOpen
			},
			set(value){
				this.$store.commit('chat/setSocket',value)
			}
		},
		intervalId:{
			get(){
				return this.$store.state.chat.intervalId
			},
			set(value){
				this.$store.commit('chat/setIntervalId',value)
			}
		},
		//计时器是否运行中
		onInterval:{
			get(){
				return this.$store.state.chat.onInterval
			},
			set(value){
				this.$store.commit('chat/setInterval',value)
			}
		},
		userInfo(){
			return this.$store.state.chat.userInfo
		}
	},
	watch:{
		'userInfo.id':function(value){
			//console.log('watch userInfo')
			this.wssInit()
		},
		'isSocketOpen':function(value){
			//console.log(value)
			if(value){
				let self=this
				let {id,nickname,figureurl}=self.userInfo,data={id,nickname,figureurl};
				/* 传送数据 */
				let tpl=JSON.stringify({controller:'User',method:'updateInfo',data})
				uni.sendSocketMessage({
					data:tpl,
					fail:function(){
						self.isSocketOpen=false
					}
				});
			}
		}
	},
	onLaunch:function(){
		//console.log('APP onLaunch')
		// #ifdef APP-PLUS
		this.setAppPuls()
		// #endif
		this.wsslistens()
		this.start()
	},
	onShow: function() {
		
	},
	onHide: function() {
		
	},
	methods:{
		...mapMutations(mapArray),
		/* 启动应用 */
		start(){
			let self=this
			this.intervalId=setInterval(()=>{
				this.ping();
			},30000);//30秒发送一次心跳
			//取得用户信息，这里做是否需要登录判断
			const tokenExpired= uni.getStorageSync('uni_id_token_expired')
			const token= uni.getStorageSync('uni_id_token')
			const userInfo= uni.getStorageSync('user_info')
			const exp=(new Date()).getTime()+60000;
			if(!tokenExpired  || !token || exp> tokenExpired  || !userInfo.id ){
				uni.clearStorage()
			}else{
				this.$store.commit('chat/setUserInfo',{...userInfo,tokenExpired,token}) 
			}
			this.$store.commit('app/appStart',true)
		},
		/* 开启websocket */
		wssInit(){
			let  url=SocketUrl,token=this.userInfo.token||null,id=this.userInfo.id||null;
			if(this.isSocketOpen){
				uni.closeSocket()
			}
			if(token && id){
				url=url+'?token='+token+'&id='+id
				uni.connectSocket({url});
			}else{
				uni.closeSocket()
				uni.removeStorage({key:'user_info'})
			}
		},
		/* 开启websocket监听 */
		wsslistens(){
			let  self=this;
			uni.onSocketOpen(function (res) {
				self.isSocketOpen=true
				console.log('WebSocket连接已打开！');
			});
			uni.onSocketMessage(function (resopnse) {
				if(!self.isSocketOpen){
					self.isSocketOpen=true
				}
				if(
					typeof resopnse.data ==='string' &&
					resopnse.data.substring(0,1)==='{' 
				){
					let obj=JSON.parse(resopnse.data);					
					if(obj.type &&  CallBack.indexOf(obj.type) >-1){
						obj.type='chat/'+obj.type
						let fn=obj.type;
						self[fn](obj);
					}
				}
			});
			uni.onSocketError(function (res) {
				self.close();
				console.log('onSocketError');
			});
			uni.onSocketClose(function (res) {
				self.close();
				console.log('onSocketClose');
			});
		},
		/* 发送连接到服务器 */
		ping(){
			const self=this;
			if(!this.onInterval){
				this.onInterval=true
			}			
			if(this.isSocketOpen ){
				this.$store.commit('log/ping',(new Date()).getTime())
				uni.sendSocketMessage({
					data:'ping',
					fail:function(){
						self.$store.commit('chat/setSocket',false)
					}
				})
			}else{
				this.wssInit()
			}
			const now=(new Date()).getTime();
			if(now+600000>this.userInfo.tokenExpired){
				this.$request('login/refreshToken',{token:this.userInfo.token})
				.then(res=>{
					this.$store.commit('log/refreshToken',res)
				})
				.catch(e=>{
					uni.closeSocket()
					uni.removeStorage({key:'user_info'})
					this.$store.commit('chat/logout')
				})
			}
		},
		close(){
			this.isSocketOpen=false
		},
		// #ifdef APP-PLUS
		setAppPuls(){
			const clientInfo = plus.push.getClientInfo()
			if(clientInfo.clientid){
				this.$store.commit('app/setClientid',clientInfo.clientid)
			}
			plus.push.addEventListener("click", function(msg) {
				
			}, false);  
			// 监听在线消息事件    
			plus.push.addEventListener("receive", function(msg) {  
				const { payload }=msg 
				const obj=JSON.parse(payload)
				const message=obj.title||'末知消息'
				plus.push.createMessage( message, payload);
			}, false);  
		}
		// #endif
	}
}